<template>
  <el-dialog
    title="新增员工"
    :visible.sync="dialogVisible"
    width="30%"
    :before-close="handleClose"
    :close-on-click-modal="false"
    center
  >
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="ruleForm.username" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="ruleForm.mobile" />
      </el-form-item>
      <el-form-item label="聘用形式" prop="formOfEmployment">
        <el-select v-model="ruleForm.formOfEmployment" placeholder="请选择聘用形式">
          <el-option label="正式" :value="1" />
          <el-option label="非正式" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="工号" prop="workNumber">
        <el-input v-model="ruleForm.workNumber" />
      </el-form-item>
      <el-form-item label="入职时间" prop="timeOfEntry">
        <el-date-picker v-model="ruleForm.timeOfEntry" type="date" placeholder="请选择入职时间" style="width: 100%;" />
      </el-form-item>
      <el-form-item label="转正时间" prop="correctionTime">
        <el-date-picker v-model="ruleForm.correctionTime" type="date" placeholder="请选择转正时间" style="width: 100%;" />
      </el-form-item>
      <el-form-item label="组织名称" prop="departmentName">
        <el-input v-model="ruleForm.departmentName" :readonly="true" placeholder="请选择组织名称" @focus="focus" />
      </el-form-item>
      <el-tree v-show="isDone" class="tree" :data="data" :props="defaultProps" :default-expand-all="true" :expand-on-click-node="false" @node-click="handleNodeClick" />
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="add">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getEmployeeList, addEmployee } from '@/api/employees'
import { getDepartments } from '@/api/departments'
import { tranListToTreeData } from '@/utils/index'
export default {
  props: ['dialogVisible', 'total'],
  data() {
    const checkPhoto = (rule, value, callback) => {
      if (/^1[3-9]\d{9}$/.test(value)) return callback()
      callback(new Error('手机号格式错误'))
    }
    const checkWorkNumber = async(rule, value, callback) => {
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      const flag = rows.some(item => item.workNumber === value)
      if (flag) {
        return callback(new Error('该工号已被使用，请重新输入'))
      }
      callback()
    }
    const checkTimeOfEntry = (rule, value, callback) => {
      if (this.ruleForm.correctionTime) {
        const timer1 = this.ruleForm.timeOfEntry.getTime() // 入职时间
        const timer2 = this.ruleForm.correctionTime.getTime() // 转正时间
        if (timer1 > timer2) return callback(new Error('日期错误'))
      }
      callback()
    }
    const checkCorrectionTime = (rule, value, callback) => {
      if (this.ruleForm.timeOfEntry) {
        const timer1 = this.ruleForm.correctionTime.getTime() // 转正时间
        const timer2 = this.ruleForm.timeOfEntry.getTime() // 入职时间
        if (timer1 < timer2) return callback(new Error('日期错误'))
      }
      callback()
    }
    return {
      ruleForm: {
        username: '',
        mobile: '',
        formOfEmployment: '', // 聘用形式
        workNumber: '', // 工号
        timeOfEntry: '', // 入职时间
        correctionTime: '', // 转正时间
        departmentName: ''
      },
      isDone: false,
      rules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 4, message: '长度在 2 到 4 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhoto, trigger: 'blur' }
        ],
        formOfEmployment: [
          { required: true, message: '请输入选择聘用形式', trigger: 'change' }
        ],
        workNumber: [
          { required: true, message: '请输入工号', trigger: 'blur' },
          { validator: checkWorkNumber, trigger: 'blur' }
        ],
        timeOfEntry: [
          { required: true, message: '请选择入职时间', trigger: 'blur' },
          { validator: checkTimeOfEntry, trigger: 'blur' }
        ],
        correctionTime: [
          { required: true, message: '请选择转正时间', trigger: 'blur' },
          { validator: checkCorrectionTime, trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '请选择组织名称', trigger: 'change' }
        ]
      },
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:dialogVisible', false)
    },
    handleNodeClick(data) {
      console.log(1)
      this.ruleForm.departmentName = data.name
      this.isDone = false
    },
    async focus() {
      const result = await getDepartments()
      this.data = tranListToTreeData(result.depts, '')
      this.isDone = true
    },
    async add() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          try {
            await addEmployee(this.ruleForm)
            this.$message({
              type: 'success',
              message: '添加成功!'
            })
            this.$emit('upDateRoles')
          } catch (error) {
            this.$message.error('添加失败')
          }
          this.$emit('update:dialogVisible', false)
        }
      })
    }
  }
}
</script>

<style>
.tree{
  margin-left: 100px;
}
</style>
